<template>
  <div class="survey-management">
    <!-- 标题 -->
    <h1>在线客户需求调研工具</h1>

    <!-- 创建新问卷按钮 -->
    <el-button type="primary" icon="el-icon-plus" @click="showSurveyEditor">创建新问卷</el-button>

    <!-- 问卷列表 -->
    <div class="survey-list">
      <el-table
        :data="surveys"
        style="width: 100%"
        border
      >
        <el-table-column prop="name" label="问卷名称"></el-table-column>
        <el-table-column prop="description" label="描述"></el-table-column>
        <el-table-column label="操作" width="350">
          <template slot-scope="scope">
            <el-button type="text" @click="viewSurvey(scope.row)">查看</el-button>
            <el-button type="text" @click="editSurvey(scope.row)">编辑</el-button>
            <el-button type="text" @click="deleteSurvey(scope.row)">删除</el-button>
            <el-button type="text" @click="shareSurvey(scope.row)">分享</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 数据统计 -->
    <div class="statistics">
      <div style="display:flex;justify-content: space-between;align-items: center">
        <h2>问卷统计数据</h2>
        <!-- 导出统计数据按钮 -->
        <el-button type="primary" icon="el-icon-download" @click="exportStatisticsToExcel">导出统计数据</el-button>
      </div>
      <el-card v-for="(stat, index) in statistics" :key="index" class="box-card">
        <div slot="header" class="clearfix">
          <span>{{ stat.name }}</span>
        </div>
        <p>总回答数: {{ stat.totalResponses }}</p>
        <p>最后更新时间: {{ stat.lastUpdated }}</p>
      </el-card>
    </div>

    <!-- 调查问卷编辑对话框 -->
    <SurveyEditor ref="surveyEditor" @created="addSurvey" @updated="updateSurvey" />

    <!-- 分享对话框 -->
    <ShareDialog ref="shareDialog" />

    <!-- 问卷详情对话框 -->
    <SurveyDetail
      ref="surveyDetail"
      :answered-surveys="answeredSurveys"
      @submitted="handleResponseSubmission"
      @storeAnsweredSurvey="updateAnsweredSurveys"
    />
  </div>
</template>

<script>
import * as XLSX from 'xlsx';
import SurveyEditor from './components/SurveyEditor.vue';
import ShareDialog from './components/ShareDialog.vue';
import SurveyDetail from './components/SurveyDetail.vue';

export default {
  components: {
    SurveyEditor,
    ShareDialog,
    SurveyDetail
  },
  data() {
    return {
      surveys: [
        // 示例数据
        { id: 1, name: '政企交付业务需求调研', description: '感谢您参与我们的需求调研问卷，您的反馈对我们非常重要！', questions: [], responses: [] },
        { id: 2, name: '产品满意度调查', description: '请对我们的产品进行满意度评价。', questions: [], responses: [] }
      ],
      statistics: [
        // 示例统计数据
        { id: 1, name: '政企交付业务需求调研', totalResponses: 0, lastUpdated: new Date().toLocaleString(), responses: [] },
        { id: 2, name: '产品满意度调查', totalResponses: 0, lastUpdated: new Date().toLocaleString(), responses: [] }
      ],
      answeredSurveys: JSON.parse(localStorage.getItem('answeredSurveys')) || []
    };
  },
  watch: {
    answeredSurveys: {
      handler(newVal) {
        localStorage.setItem('answeredSurveys', JSON.stringify(newVal));
      },
      deep: true
    }
  },
  beforeDestroy() {
    localStorage.removeItem('answeredSurveys');
  },
  methods: {
    showSurveyEditor() {
      this.$refs.surveyEditor.open();
    },
    viewSurvey(survey) {
      this.$refs.surveyDetail.open(survey);
    },
    editSurvey(survey) {
      this.$refs.surveyEditor.open(survey);
    },
    deleteSurvey(survey) {
      this.surveys = this.surveys.filter(item => item.id !== survey.id);
      this.statistics = this.statistics.filter(stat => stat.id !== survey.id);
      this.$message.success('问卷删除成功');
    },
    addSurvey(newSurvey) {
      newSurvey.id = this.surveys.length + 1;
      newSurvey.responses = []; // 初始化响应数组
      this.surveys.push(newSurvey);
      this.statistics.push({
        id: newSurvey.id,
        name: newSurvey.name,
        description: newSurvey.description,
        totalResponses: 0,
        lastUpdated: new Date().toLocaleString(),
        responses: []
      });
      this.$message.success('问卷创建成功');
    },
    updateSurvey(updatedSurvey) {
      const index = this.surveys.findIndex(survey => survey.id === updatedSurvey.id);
      if (index !== -1) {
        this.surveys.splice(index, 1, updatedSurvey);
        const statIndex = this.statistics.findIndex(stat => stat.id === updatedSurvey.id);
        if (statIndex !== -1) {
          this.statistics[statIndex].name = updatedSurvey.name;
          this.statistics[statIndex].description = updatedSurvey.description;
          this.statistics[statIndex].lastUpdated = new Date().toLocaleString();
        }
        this.$message.success('问卷更新成功');
      } else {
        this.$message.error('未找到要更新的问卷');
      }
    },
    handleResponseSubmission(data) {
      const { surveyId, responses } = data;
      const surveyIndex = this.surveys.findIndex(survey => survey.id === surveyId);
      if (surveyIndex !== -1) {
        this.surveys[surveyIndex].responses.push(responses); // 添加响应到问卷中
        this.statistics[surveyIndex].totalResponses += 1;
        this.statistics[surveyIndex].lastUpdated = new Date().toLocaleString();
        this.statistics[surveyIndex].responses.push(responses); // 添加响应到统计数据中
        this.$message.success('统计数据已更新');
      }
    },
    exportStatisticsToExcel() {
      const worksheetData = [];
      worksheetData.push(['问卷ID', '问卷名称', '描述', '总回答数', '最后更新时间']);

      this.statistics.forEach(stat => {
        worksheetData.push([
          stat.id,
          stat.name,
          stat.description,
          stat.totalResponses,
          stat.lastUpdated
        ]);
      });

      // Ensure there are statistics before creating the worksheet
      if (worksheetData.length <= 1) {
        this.$message.warning('没有可导出的数据');
        return;
      }

      const worksheet = XLSX.utils.aoa_to_sheet(worksheetData);
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
      XLSX.writeFile(workbook, '问卷统计数据.xlsx');
    },
    shareSurvey(survey) {
      const url = `${window.location.origin}/survey/${survey.id}`;
      this.$refs.shareDialog.open(url);
    },
    updateAnsweredSurveys(data) {
      this.answeredSurveys.push(data);
    }
  }
};
</script>

<style scoped lang="scss">
.survey-management {
  padding: 20px;
  height: calc(100vh - 60px);
  overflow: hidden auto;
}

.survey-list {
  margin-top: 20px;
}

.statistics {
  margin-top: 40px;
}

.box-card {
  margin-bottom: 20px;
}
</style>
